package com.sgc.view;

import java.security.MessageDigest;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import com.architecture.view.MensagemEnum;
import com.architecture.view.PadraoManutencaoMB;
import com.architecture.view.UtilWeb;
import com.archtecture.control.enums.Mensagem;
import com.archtecture.control.exceptions.NegocioException;
import com.sgv.model.entities.UsuarioModel;
import com.sgv.model.persistence.UsuarioFacadeLocal;
import com.sun.mail.util.BASE64EncoderStream;

import org.jboss.security.auth.spi.Util;

@ManagedBean
@ViewScoped
public class UsuarioMB extends PadraoManutencaoMB<UsuarioModel> {

	@EJB
	private UsuarioFacadeLocal facade;

	@PostConstruct
	private void iniciarComponentes() {
		try {
			setModelCad(facade.obterUsuarioLogado());
		}
		catch (NegocioException e) {
			UtilWeb.tratarException(e);
		}
	}

	public boolean isPossuiSenhaPadrao() throws NegocioException {
		return facade.verificaUsuarioSenhaPadrao();
	}

	@Override
	protected UsuarioModel getInstance() {
		UsuarioModel lModel = new UsuarioModel();
		return lModel;
	}

	@Override
	protected void prepararEditar() throws NegocioException {

		if (getModelCad().getSenha().isEmpty() || !getModelCad().getSenha().equals(getModelCad().getSenhaConfirm())) {
			throw new NegocioException(Mensagem.ERRO_CONFIRMACAO_SENHA);
		}

		getModelCad().setSenha(Util.createPasswordHash("SHA-256", "base64", "UTF-8", getModelCad().getLogin(), getModelCad().getSenha()));
	}

	public void executarSalvar() {

		try {

			prepararEditar();
			getPersistenceFacade().atualizar(getModelCad());
			UtilWeb.enviarMensagem(MensagemEnum.INFO_SUCESSO_EDICAO);

			aposSalvar();
		}
		catch (NegocioException e) {
			UtilWeb.tratarException(e);
		}
	}
}
